'use strict';

const BaseController = require('./base');

class CategoriesController extends BaseController {
  // 查询
  async index() {
    /** 
    const { ctx } = this; // categories?page=1&pageSize=5&keyword=a
    let {pageNum=1, pageSize=5, keyword} = ctx.query;
    pageNum = isNaN(pageNum)? 1: parseInt(pageNum);
    pageSize = isNaN(pageSize)? 5: parseInt(pageSize);
    let query = {};
    if (keyword) {
      query.name = new RegExp(keyword);
    }

    try {
      // skip跳过执行条数
      let items = await ctx.model.Category.find(query)
          .skip((pageNum - 1) * pageSize)
          .limit(pageSize);
      this.success(items)
    } catch (error) {
      this.error(error);
    }
    */

    try {
      // 使用封装的方法进行请求
      await this.getPager({modelName: 'Category', fields: ['name']});
    } catch (error) {
      this.error(error);
    }

  }
  // 增加文章分类
  async create() {
    const { ctx } = this;

    let category = ctx.request.body;
    try {
      let doc = await ctx.model.Category.findOne(category);
      if (doc) {
        this.error('此分类已经存在！')
      }else{
        doc = await ctx.model.Category.create(category);
        this.success('保存分类成功')
      }
      
    } catch (error) {
      this.error(error);
    }
    
  }

  async update() {
    const { ctx } = this;
    // api/categories/:id
    // 通过以下方式来取参数
    let id = ctx.params.id;
    let category = ctx.request.body;

    try {
      let result = await ctx.model.Category.findByIdAndUpdate(id, category);
      this.success('更新成功');
    } catch (error) {
      this.error(error);
    }
  }

  async destroy() {
    const { ctx } = this;
    let id = ctx.params.id;
    // 能够同时支持
    let {ids = []} = ctx.request.body;
    ids.push(id)
    try {
      // await ctx.model.Category.findByIdAndRemove(id); 删除单个
      await ctx.model.Category.remove({_id: {$in: ids}});
      this.success('删除成功');
    } catch (error) {
      this.error(error);
    }
    
  }

}

module.exports = CategoriesController;